package cn.signalpha.modules.resource.builder.oss;

import cn.signalpha.common.enums.StatusEnum;
import cn.signalpha.core.cache.utils.CacheUtil;
import cn.signalpha.core.log.exception.ServiceException;
import cn.signalpha.core.oss.OssTemplate;
import cn.signalpha.core.oss.enums.OssEnum;
import cn.signalpha.core.oss.props.OssProperties;
import cn.signalpha.core.oss.rule.BladeOssRule;
import cn.signalpha.core.oss.rule.OssRule;
import cn.signalpha.core.tool.utils.Func;
import cn.signalpha.core.tool.utils.StringPool;
import cn.signalpha.core.tool.utils.StringUtil;
import cn.signalpha.core.tool.utils.WebUtil;
import cn.signalpha.modules.resource.entity.Oss;
import cn.signalpha.modules.resource.service.IOssService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static cn.signalpha.core.cache.constant.CacheConstant.RESOURCE_CACHE;

/**
 * Oss云存储统一构建类
 */
public class OssBuilder {

	public static final String OSS_CODE = "oss:code:";
	public static final String OSS_PARAM_KEY = "code";

	private final OssProperties ossProperties;
	private final IOssService ossService;

	public OssBuilder(OssProperties ossProperties, IOssService ossService) {
		this.ossProperties = ossProperties;
		this.ossService = ossService;
	}

	/**
	 * OssTemplate配置缓存池
	 */
	private final Map<String, OssTemplate> templatePool = new ConcurrentHashMap<>();

	/**
	 * oss配置缓存池
	 */
	private final Map<String, Oss> ossPool = new ConcurrentHashMap<>();

	/**
	 * 获取template
	 *
	 * @return OssTemplate
	 */
	public OssTemplate template() {
		return template(StringPool.EMPTY);
	}

	/**
	 * 获取template
	 *
	 * @param code 资源编号
	 * @return OssTemplate
	 */
	public OssTemplate template(String code) {
		Oss oss = getOss(code);
		Oss ossCached = ossPool.get(code);
		OssTemplate template = templatePool.get(code);
		// 若为空或者不一致，则重新加载
		if (Func.hasEmpty(template, ossCached) || !oss.getEndpoint().equals(ossCached.getEndpoint()) || !oss.getAccessKey().equals(ossCached.getAccessKey())) {
			synchronized (OssBuilder.class) {
				template = templatePool.get(code);
				if (Func.hasEmpty(template, ossCached) || !oss.getEndpoint().equals(ossCached.getEndpoint()) || !oss.getAccessKey().equals(ossCached.getAccessKey())) {
					OssRule ossRule = new BladeOssRule(Boolean.FALSE);;
					if (oss.getCategory() == OssEnum.MINIO.getCategory()) {
						template = MinioOssBuilder.template(oss, ossRule);
					} else if (oss.getCategory() == OssEnum.QINIU.getCategory()) {
						template = QiniuOssBuilder.template(oss, ossRule);
					} else if (oss.getCategory() == OssEnum.ALI.getCategory()) {
						template = AliOssBuilder.template(oss, ossRule);
					} else if (oss.getCategory() == OssEnum.TENCENT.getCategory()) {
						template = TencentCosBuilder.template(oss, ossRule);
					} else if (oss.getCategory() == OssEnum.HUAWEI.getCategory()) {
						template = HuaweiObsBuilder.template(oss, ossRule);
					} else if (oss.getCategory() == OssEnum.AMAZONS3.getCategory()) {
						template = AmazonS3OssBuilder.template(oss, ossRule);
					}
					templatePool.put(code, template);
					ossPool.put(code, oss);
				}
			}
		}
		return template;
	}

	/**
	 * 获取对象存储实体
	 *
	 * @return Oss
	 */
	public Oss getOss(String code) {
		LambdaQueryWrapper<Oss> lqw = Wrappers.<Oss>query().lambda();
		// 获取传参的资源编号并查询，若有则返回，若没有则调启用的配置
		String ossCode = StringUtil.isBlank(code) ? WebUtil.getParameter(OSS_PARAM_KEY) : code;
		if (StringUtil.isNotBlank(ossCode)) {
			lqw.eq(Oss::getOssCode, ossCode);
		} else {
			ossCode = "enable";
			lqw.eq(Oss::getStatus, StatusEnum.ON.getType());
		}
		Oss oss = CacheUtil.get(RESOURCE_CACHE, OSS_CODE, ossCode, () -> {
			Oss o = ossService.getOne(lqw);
			// 若为空则调用默认配置
			if (o == null || o.getId() == null) {
				Oss defaultOss = new Oss();
				defaultOss.setId(0L);
				defaultOss.setCategory(OssEnum.of(ossProperties.getName()).getCategory());
				defaultOss.setEndpoint(ossProperties.getEndpoint());
				defaultOss.setTransformEndpoint(ossProperties.getTransformEndpoint());
				defaultOss.setBucketName(ossProperties.getBucketName());
				defaultOss.setAccessKey(ossProperties.getAccessKey());
				defaultOss.setSecretKey(ossProperties.getSecretKey());
				defaultOss.setAppId(ossProperties.getAppId());
				defaultOss.setRegion(ossProperties.getRegion());
				return defaultOss;
			} else {
				return o;
			}
		}, false);
		if (oss == null || oss.getId() == null) {
			throw new ServiceException("未获取到对应的对象存储配置");
		} else {
			return oss;
		}
	}

}
